package org.zappee.dannyt.cairngorm.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import org.zappee.dannyt.cairngorm.business.Bug;
	import org.zappee.dannyt.cairngorm.event.SaveBugEvent;
	import org.zappee.dannyt.cairngorm.model.ModelLocator;

	public class SaveBugCommand implements ICommand
	{
		private var _model:ModelLocator;
		
		public function SaveBugCommand()
		{
		}
		
		public function execute(event:CairngormEvent):void
		{
			var saveBugEvent:SaveBugEvent = SaveBugEvent(event);
			this._model = ModelLocator.getInstance();
			var bug:Bug = saveBugEvent.bug;
			if(bug.Id > 0)
				saveExistingBug(bug);
			else
				saveNewBug(bug);
			this._model.viewState = ModelLocator.VIEWING_BUG_LIST_SCREEN;
		}
		
		private function saveExistingBug(bug:Bug):void
		{
			for each(var b:Bug in this._model.bugs)
			{
				if(b.Id == bug.Id)
				{
					b = bug;
				}
			}
		}
		private function saveNewBug(bug:Bug):void
		{
			bug.Id = this._model.lastBugId++;
			this._model.bugs.addItem(bug);
		}
	}
}